package com.daisuxia.task;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.risk.dao.IRiskCreditUserDao;
import com.daisuxia.risk.pojo.RiskCreditUser;
import com.daisuxia.risk.service.IJxlService;
import com.daisuxia.risk.service.IRiskCreditUserService;
import com.daisuxia.risk.service.IZzcService;
import com.daisuxia.risk.utils.ConstantRisk;
import com.daisuxia.risk.utils.RandomUtils;
import com.daisuxia.risk.utils.RiskCreditUserUtil;
import com.daisuxia.risk.utils.ThreadPool;
import com.daisuxia.risk.utils.ThreadPool2;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.ChannelInfo;
import com.daisuxia.web.pojo.PhoneUrl;
import com.daisuxia.web.service.IBackConfigParamsService;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IChannelInfoService;
import com.daisuxia.web.service.IPhoneUrlService;
import com.daisuxia.web.service.IRepaymentService;
import com.daisuxia.web.util.PageConfig;

import redis.clients.jedis.JedisCluster;

/**
 * 
 * @author zhangsh Tel:13817876783
 * @date 2017年9月20日 下午2:05:48
 * @Title: RiskManageTaskService
 * @ClassName: RiskManageTaskService
 * @Description:
 */

public class RiskManageTaskService {
	private static Logger logger = LoggerFactory.getLogger(RiskManageTaskService.class);
	@Autowired
	JedisCluster jedisCluster;
	@Autowired
	private IRiskCreditUserDao riskCreditUserDao;
	@Autowired
	private IRiskCreditUserService riskCreditUserService;
	@Autowired
	private IJxlService jxlService;
	@Autowired
	private IBackConfigParamsService backConfigParamsService;
	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private IChannelInfoService channelInfoService;
	@Autowired
	private IPhoneUrlService iPhoneUrlService;
	@Autowired
	private IRepaymentService repaymentService;
	
	@Autowired
	private IZzcService zzcService;
	
	
	
	
	int day = 2 * 60 * 24;
	/**
	 * 每隔2分钟获取聚信立报告
	 * @author zhangsh Tel:13817876783
	 * @date 2017年9月21日 上午11:37:52
	 * @Title findJxlReport
	 * @Description  void 
	 * @throws
	 */
	public void findJxlReport() {
//		
		LinkedHashMap<String, String> mapApi = SysCacheUtils.getConfigParams(BackConfigParams.YANGYUE_MDL_API);
		String shortSmsOpen = mapApi.get(BackConfigParams.SHORT_SMS_OPEN);
		String jxlReportOpen = mapApi.get(BackConfigParams.JXL_REPORT_OPEN);
		if(!jxlReportOpen.equals("1")){
			logger.info("------ jxlReportOpen was closed!!!");
			return;
		}
		
		logger.info("------ jxlReportOpen is open!!!");


		logger.info("findJxlReport is running");
		String key2 = ConstantRisk.JXL_WAIT_ANALYSIS;
		if (jedisCluster.get(key2) != null) {
			logger.info("last findJxlReport is running");
		} else {
			try {
				jedisCluster.setex(key2, ConstantRisk.FLAG_SECOND * day, key2);
				HashMap<String, Object> params = new HashMap<String, Object>();
				Integer size = 5;
				params.put(Constant.PAGE_SIZE, size);
				int totalPageNum = riskCreditUserDao.findJxlWaitReportCount(params);
				int total = 0;
				if (totalPageNum > 0) {
					if (totalPageNum % size > 0) {
						total = totalPageNum / size + 1;
					} else {
						total = totalPageNum / size;
					}
				}
				for (int i = 0; i < total; i++) {
					params.put(Constant.CURRENT_PAGE, i);
					PageConfig<HashMap<String, Object>> pm = riskCreditUserService.findJxlPage(params);
					List<HashMap<String, Object>> list = pm.getItems();
					if (list != null && list.size() > 0) {
					
							for (final HashMap<String, Object> map : list) {
								
								String value = map.get("userId") + "";
								String phone=map.get("userName")+"";
								String channelCode=map.get("userFrom")+"";
								if(!shortSmsOpen.equals("1")){
									logger.info("this shortSmsOpen was closed!");
//									continue;
								}else{
									logger.info("this user_id is running "+value);
									if(!verifyChannelSource(channelCode,phone)){
										riskCreditUserDao.updateNew4Flag(Integer.parseInt(value));
										logger.info("this phone number "+phone+" is not from ours channel ");
										continue;
									}
								}
								
								logger.info("normal go  =====================================================================");
								
								final String key = ConstantRisk.JXL_REPORT + value;
								try {
									if (jedisCluster.get(key) != null) {
										logger.info("others is findJxlReport key=" + key);
									} else {
										jedisCluster.setex(key, ConstantRisk.FLAG_SECOND * day, value);
										ThreadPool.getInstance().run(new Runnable() {
											@Override
											public void run() {
												HashMap<String, Object> map1 = new HashMap<String, Object>();
												map1.putAll(map);
											
												try {
													ServiceResult serviceResult = jxlService.findUserReport(map1);
													if (serviceResult.isSuccessed()) {
														map1.put("detail", serviceResult.getMsg());
														RiskCreditUser riskCreditUser3 = RiskCreditUserUtil.getInstance().createJxl(map1);
														if (riskCreditUser3 != null) {
															riskCreditUserService.updateJxl(riskCreditUser3);
														} else {
															// jedisCluster.del(key);
															logger.info("updateJxl error riskCreditUser3=" + riskCreditUser3);
														}
													}
												} catch (Exception e) {
													jedisCluster.del(key);
													logger.error("findJxlReport error map1=" + map1);
												} finally {
													jedisCluster.del(key);
												}
	
												// }
											}
										});
									}
	
								} catch (Exception e) {
									jedisCluster.del(key);
									logger.error("findJxlReport error map=" + map, e);
								}
								
								
							}
							list = null;
							
							
					} else {
						break;
					}
				}
			} catch (Exception e) {
				jedisCluster.del(key2);
				logger.error("findJxlReport error ", e);
			} finally {
				jedisCluster.del(key2);
			}
		}
	}
	/**
	 * 验证是不是我们渠道里过来的
	 * @author zhangsh Tel:13817876783
	 * @date 2017年9月29日 下午5:01:17
	 * @Title verifyChannelSource
	 * @Description 
	 * @param phone
	 * @return boolean 
	 * @throws
	 */
	private boolean verifyChannelSource(String channelId,String phone) {
		if(channelId!=null&&!"null".equals(channelId)){
			ChannelInfo channelInfo=channelInfoService.findOneChannelInfoById(Integer.parseInt(channelId));
			if(null!=channelInfo){
				
			Integer channelType=channelInfo.getChannelType();
			if(channelType!=null){
				if(1==channelType.intValue()){//短连接
					Map<String, Object> params =new HashMap<String, Object>();
					params.put("phone", phone);
					List<PhoneUrl> list=iPhoneUrlService.findAll(params);
					if(list!=null&&list.size()>0){
						logger.info("this phone number "+phone+" comes from channel "+channelId+", channel name "+channelInfo.getChannelName()+",  channelType  is "+channelType);
						return true;
					}
				}else{//非短连接
					if(phone.equals(channelInfo.getChannelTel())){
						Integer crossRate=channelInfo.getCrossRate();
						if(null!=crossRate){
							int randomInt=RandomUtils.RandomProducer().intValue();
							logger.info("this phone number "+phone+" comes from channel "+channelId+", channel name "+channelInfo.getChannelName()+",  random int is "+randomInt+",  crossRate int  is "+crossRate);
							if(crossRate.intValue()<=randomInt&&randomInt<=10*crossRate){
								logger.info("fire this phone number "+phone+" comes from channel "+channelId+", channel name "+channelInfo.getChannelName()+",  random int is "+randomInt+",  crossRate int  is "+crossRate);
								return true;
							}
						}
						
						
					}
				}
			}
				
				
			}
		}
		
		return false;
	}
	/**
	 * 验证是不是我们短连接推广过来的
	 * @author zhangsh Tel:13817876783
	 * @date 2017年9月29日 下午5:01:44
	 * @Title verifyShortSms
	 * @Description 
	 * @param phone
	 * @return boolean 
	 * @throws
	 */
	/*private boolean verifyShortSms(String phone) {
		Map<String, Object> params =new HashMap<String, Object>();
		params.put("phone", phone);
		List<PhoneUrl> list=iPhoneUrlService.findAll(params);
		if(list!=null&&list.size()>0){
			return true;
		}
		
		return false;
	}*/
	/**
	 * 更新认证完毕的新用户的借款额度
	 * @author zhangsh Tel:13817876783
	 * @date 2017年9月20日 下午2:10:10
	 * @Title updateEd
	 * @Description  void 
	 * @throws
	 */
	public void updateEd() {
		logger.info("updateEd is running");
		String key2 = ConstantRisk.CAL_MONEY;
		if (jedisCluster.get(key2) != null) {
			logger.info("last updateEd is running");
		} else {
			jedisCluster.setex(key2, ConstantRisk.FLAG_SECOND * day, key2);
			try {
				HashMap<String, Object> params2 = new HashMap<String, Object>();
				Integer size = 5;
				params2.put(Constant.PAGE_SIZE, size);
				int totalPageNum = riskCreditUserDao.findCalMoneyCount(params2);
				int total = 0;
				if (totalPageNum > 0) {
					if (totalPageNum % size > 0) {
						total = totalPageNum / size + 1;
					} else {
						total = totalPageNum / size;
					}
				}
				for (int i = 0; i < total; i++) {
					params2.put(Constant.CURRENT_PAGE, i);
					PageConfig<RiskCreditUser> pm = riskCreditUserService.findCalPage(params2);
					List<RiskCreditUser> list = pm.getItems();
					if (list != null && list.size() > 0) {
						for (final RiskCreditUser riskCreditUser : list) {
							String value = riskCreditUser.getUserId() + "";
							final String key = ConstantRisk.USER_MONEY + value;
							if (jedisCluster.get(key) != null) {
								logger.info("others is updateEd key=" + key);
							} else {
								try {
									jedisCluster.setex(key, ConstantRisk.FLAG_SECOND * day, value);
									ThreadPool.getInstance().run(new Runnable() {
										@Override
										public void run() {
											// if
											// (riskCreditUserDao.findEdHelp(riskCreditUser)
											// <= 0) {
											// logger.info("ed redis is null but db had deal");
											// } else {
											try {
												riskCreditUserService.updateBorrowMoney(riskCreditUser);
											} catch (Exception e) {
												jedisCluster.del(key);
												logger.error("updateEd error riskCreditUser=" + riskCreditUser);
											} finally {
												jedisCluster.del(key);
											}
											// }
										}
									});
								} catch (Exception e) {
									jedisCluster.del(key);
									logger.error("updateEd error riskCreditUser=" + riskCreditUser, e);
								}
							}

						}
						list = null;
					} else {
						break;
					}
				}
			} catch (Exception e) {
				jedisCluster.del(key2);
				logger.error("updateEd error ", e);
			} finally {
				jedisCluster.del(key2);
			}
		}
	}
	/**
	 * 新风控规则转换
	 * @author zhangsh Tel:13817876783
	 * @date 2017年9月21日 下午1:18:37
	 * @Title updateFromRisk
	 * @Description  void 
	 * @throws
	 */
	public void updateFromRisk() {
		
		logger.info(" updateFromRisk is running ");
		String key2 = "TO_NEW_RISK";
		if (jedisCluster.get(key2) != null) {
			logger.info("last updateAnalysis is running");
			jedisCluster.del(key2);
		} else {
			try {
				jedisCluster.setex(key2, ConstantRisk.FLAG_SECOND * day, key2);
				riskCreditUserService.updateFromRisk();
			} catch (Exception e) {
				logger.error("task updateFromRisk error ", e);
			} finally {
				jedisCluster.del(key2);
			}
		}
	}
	
	/**
	 * 新老用户在此审核
	 * @author zhangsh Tel:13817876783
	 * @date 2017年9月18日 上午10:26:14
	 * @Title updateAnalysis
	 * @Description  void 
	 * @throws
	 */
	public void updateAnalysis() {
		Map<String, String> map = SysCacheUtils.getConfigMap(BackConfigParams.SYSTEM);
		int limit = Integer.valueOf(map.get("SYSTEM_NEW_RISK"));
		String newRiskKey = "newRiskKey";
		logger.info("updateAnalysis is running");
		String key2 = ConstantRisk.RISK_ANALYSIS;
		if (jedisCluster.get(key2) != null) {
			logger.info("last updateAnalysis is running");
		} else {
			try {

				//获取老用户开关 1机审 0人工审核
				HashMap<String, Object> paramsback = new HashMap<String, Object>();
				paramsback.put("sysType", "SYS_NOCACHE");
				paramsback.put("sysKey", "OLDU_SWITCH");
				//params.put("sysName","");
				List<BackConfigParams> listback = backConfigParamsService.findParams(paramsback);
				String offon = "1";
				if (listback.size() == 1) {
					offon = listback.get(0).getSysValue();
				}
				//是老用户 true 人工 false 机器
				boolean oldswitch = "0".equals(offon);

				logger.info("updateAnalysis oldu switch =" + offon);
				int sub = ConstantRisk.FLAG_SECOND * day;
				String riskValue = jedisCluster.get(newRiskKey);
				if (riskValue == null) {
					riskValue = "0";
				}
				int riskCount = Integer.valueOf(riskValue);
				jedisCluster.setex(key2, ConstantRisk.FLAG_SECOND * day, key2);
				HashMap<String, Object> params2 = new HashMap<String, Object>();
				Integer size = 5;
				params2.put(Constant.PAGE_SIZE, size);
				int totalPageNum = riskCreditUserDao.findWaitAnalysisCount(params2);
				int total = 0;
				if (totalPageNum > 0) {
					if (totalPageNum % size > 0) {
						total = totalPageNum / size + 1;
					} else {
						total = totalPageNum / size;
					}
				}
				for (int i = 0; i < total; i++) {
					params2.put(Constant.CURRENT_PAGE, i);
					PageConfig<HashMap<String, Object>> pm = riskCreditUserService.findAnalysisPage(params2);
					List<HashMap<String, Object>> list = pm.getItems();
					if (list != null && list.size() > 0) {
						for (final HashMap<String, Object> params : list) {
							String value = params.get("assetId") + "";
							final String key = ConstantRisk.REVIEW_BORROW + value;
							riskCount += 1;

							// 控制一天发送新模型风控的个数
							//查看是否是老用户
							boolean finallikd = false;
							try {
								BorrowOrder borrowOrder = borrowOrderService.findOneBorrow(Integer.parseInt(value));
								if (borrowOrder != null) {
									finallikd = 1 == borrowOrder.getCustomerType();
								}
							} catch (NumberFormatException e) {
								logger.error("updateAnalysis oldu switch cast=NumberFormatException:" + value);
							}
							// true 老用户人工审核  false 机器审核
							boolean tempboo = finallikd && oldswitch;

							final boolean flag = (riskCount <= limit)&&!tempboo;
							if (flag) {
								Calendar cal = Calendar.getInstance();
								cal.setTime(new Date());
								cal.set(Calendar.HOUR_OF_DAY, 23);
								cal.set(Calendar.MINUTE, 59);
								cal.set(Calendar.SECOND, 59);
								int tmp = Integer.valueOf((cal.getTimeInMillis() - System.currentTimeMillis()) / 1000 + "");
								if (tmp > 0) {
									sub = tmp;
								}
								jedisCluster.setex(newRiskKey, sub, riskCount + "");
							}
							try {
								if (jedisCluster.get(key) != null) {
									logger.info("others is reviews key=" + key);
								} else {
									jedisCluster.setex(key, ConstantRisk.FLAG_SECOND * day, value);
									ThreadPool2.getInstance().run(new Runnable() {
										@Override
										public void run() {
											// if
											// (riskCreditUserDao.findAnalysisHelp(value)
											// <= 0) {
											// logger.info("analysis redis is null but db had deal");
											// } else {
											try {
												riskCreditUserService.updateAll(params, flag);
											} catch (Exception e) {
												jedisCluster.del(key);
												logger.error("updateAnalysis params=" + params);
											} finally {
												jedisCluster.del(key);
											}
											// }
										}
									});
								}
							} catch (Exception e) {
								jedisCluster.del(key);
								logger.error("updateAnalysis error params=" + params, e);
							}
						}
						list = null;
					} else {
						break;
					}
				}
			} catch (Exception e) {
				jedisCluster.del(key2);
				logger.error("updateAnalysis error ", e);
			} finally {
				jedisCluster.del(key2);
			}
		}
	}
	


}